<template>
  <div>
    <tableComponents :isShow="false" @toAdd="openDio" :isHaveExport="false" :isHavePagination="false">
      <template v-slot:table>
        <el-table v-loading="loading" row-key="id" element-loading-text="拼命加载中" ref="multipleTable" :data="materialList" stripe
            header-row-class-name="head_color" tooltip-effect="dark" style="width: 99.9%">
          <el-table-column label="标题" min-width="100">
            <template slot-scope="scope">{{ scope.row.title }}</template>
          </el-table-column>
          <el-table-column label="模板id" min-width="250">
            <template slot-scope="scope">{{ scope.row.templet_id }}</template>
          </el-table-column>
          <el-table-column label="小程序模板id" min-width="250">
            <template slot-scope="scope">{{
              scope.row.templet_applets_id
            }}</template>
          </el-table-column>

          <el-table-column label="模板内容" min-width="300">
            <template slot-scope="scope">{{ scope.row.templet }}</template>
          </el-table-column>
          <el-table-column label="操作" min-width="250">
            <template slot-scope="scope">
              <el-button :loading="$store.state.isLoading" size="mini" type="primary" @click="toItems(scope.row.id)">管理</el-button>
              <el-button :loading="$store.state.isLoading" size="mini" type="primary" @click="updateItem(scope.$index, scope.row)">编辑</el-button>
              <el-button :loading="$store.state.isLoading" size="mini" type="danger" @click="deleteItems(scope.$index, scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </tableComponents>

    <el-dialog :close-on-click-modal="false" title="模板管理" v-loading="dioLoading" class="tl size_13" width="800px" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="formYZ" ref="form" :label-width="formLabelWidth">
        <el-form-item label="标题" prop="title">
          <el-col :span="15">
            <el-input v-model="form.title" autocomplete="off"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="模板id" prop="templet_id">
          <el-col :span="15">
            <el-input v-model="form.templet_id" autocomplete="off"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="小程序模板id" prop="templet_id">
          <el-col :span="15">
            <el-input v-model="form.templet_applets_id" autocomplete="off"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="模板内容" prop="templet">
          <el-col :span="15">
            <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" v-model="form.templet" autocomplete="off"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-button :loading="$store.state.isLoading" type="primary" @click="submitForm('form')">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import HeadTitle from "@/components/currency/HeadTitle.vue";
import Sortable from "sortablejs";
export default {
  components: {
    HeadTitle
  },
  data () {
    return {
      materialList: [],
      dialogFormVisible: false,
      dioLoading: false,
      multipleSelection: [],
      uddateIndex: "",
      form: {
        title: "",
        templet_id: "",
        templet: "",
        templet_applets_id: ""
      },
      formLabelWidth: "100px",
      fileList2: [],
      formYZ: {
        title: [{ required: true, message: "标题不能为空", trigger: "blur" }]
        // templet_id:[
        //      { required: true, message: '模板不能为空', trigger: 'blur' },
        // ],
        // templet:[
        //      { required: true, message: '模板内容不能为空', trigger: 'blur' },
        // ],
      },
      loading: false
    };
  },
  methods: {
    openDio () {
      this.dialogFormVisible = true;
      this.form = {
        title: "",
        templet_id: "",
        templet: "",
        templet_applets_id: ""
      };
    },
    getMaterialList () {
      this.loading = true;
      var data = {};
      this.$api.getWechat.getTemplateList(data).then(res => {
        if (res.data.code == 200 && res.data.status == 1) {
          this.materialList = res.data.result;
        }
        this.loading = false;
      });
      this.loading = false;
    },
    handleSelectionChange (val) {
      this.multipleSelection = val;
    },
    deleteItems (index, id) {
      this.$swal({
        title: "您确定要删除这条信息吗",
        text: "删除后将无法恢复，请谨慎操作！",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "是的，我要删除",
        cancelButtonText: "容我三思"
      }).then(willDelete => {
        if (willDelete.value) {
          var data = { id };
          this.$api.getWechat.deleteTemplateItem(data).then(res => {
            if (res.data.code == 200) {
              this.$swal("删除成功！", "您已经删除了这条信息。", "success");
              // this.getMaterialList();
              this.materialList.splice(index, 1);
            } else {
              this.$swal("删除失败！", "出错啦！", "success");
            }
          });
        }
      });
    },
    submitForm (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.dioLoading = true;
          var params = this.form;
          var _this = this;
          if (params.id) {
            this.$api.getWechat.updateTemplateItem(params).then(res => {
              if (res.data.code == 200 && res.data.result != null) {
                // this.getMaterialList();

                this.$fnc.alertSuccess({ text: "修改成功" }); //成功弹出框
                this.materialList[this.uddateIndex] = _this.form;
                // this.$refs[formName].resetFields();
              } else {
                this.$fnc.alertError(res.data.code_desc, res.data.result); //失败弹出框
              }
            });
          } else {
            this.$api.getWechat.addTemplateItem(params).then(res => {
              if (res.data.code == 200 && res.data.result != null) {
                this.$fnc.alertSuccess({ text: "添加成功" }); //成功弹出框
                this.materialList.push(_this.form);
              } else {
                this.$fnc.alertError(res.data.code_desc, res.data.result); //失败弹出框
              }
            });
          }
          this.dioLoading = false;
          this.dialogFormVisible = false;
        } else {
          return false;
        }
      });
    },
    updateItem (index, row) {
      this.uddateIndex = index;
      this.dialogFormVisible = true;
      this.form = row;
    },
    toItems (id) {
      this.$store.commit("addbreadcrumbs", {
        title: "管理",
        url: `/index/wechat/wxinfo`
      });
      this.$store.commit("setSmsId", id);
      this.$router.push("/index/wechat/wxinfo");
    },
    rowDrop () {
      const tbody = document.querySelector(".el-table__body-wrapper tbody");
      const _this = this;
      var aa = Sortable.create(tbody, {
        onEnd ({ newIndex, oldIndex }) {
          console.log("new" + newIndex);
          console.log("old" + oldIndex);

          const currRow = _this.materialList[oldIndex];
          _this.materialList.splice(oldIndex, 1);
          _this.materialList.splice(newIndex, 0, currRow);

          console.log(_this.materialList);
          var data = {};
          var sort_str = [];
          for (var i in _this.materialList) {
            sort_str.push(_this.materialList[i].id);
          }
          data.sort_str = sort_str.join("@");
          if (data.sort_str) {
            _this.$api.getWechat.sortTemplate(data).then(res => {
              console.log(res);
              if (!res.data.result) {
                _this.$fnc.alertError(res.data.code_desc, res.data.result);
              }
            });
          }
        }
      });
    }
  },
  mounted () {
    this.getMaterialList();
    this.rowDrop();
  },
  watch: {}
};
</script>
